const express = require("express")
const app = express()
const cors = require('cors')
const router = require("./router")
const userRoutes = require('./routes/userRoutes')
const chatroomRoutes = require('./routes/chatroomRoutes')
const messageRoutes = require('./routes/messageRoutes')
const visitorRoutes = require('./routes/visitorRoutes')
const http = require('http')
const server = http.createServer(app)
const initializeSocket = require('./socket/socketManager')

// 允许特定来源的请求
const allowedOrigins = ['http://8.138.152.233:5051', 'http://localhost:5051', 'http://zouyangguang.cn', 'https://zouyangguang.cn', 'https://8.138.152.233:5051', 'https://localhost:5051'];

app.use(cors({
  origin: function (origin, callback) {
    if (allowedOrigins.includes(origin)) {
      return callback(null, true); // 如果来源在允许列表中，则允许
    } else if (origin == undefined) {
      return callback(null, true);
    } else {
      const text = "请访问: http://8.138.152.233:5051 \n你小子! 你不是我的人! (╯‵□′)╯炸弹！•••*～●\n资源已被保护"
      return callback(text, false)
    }
  },
  credentials: true // 允许凭证
}));

//配置静态资源
app.use(express.static("./public"))
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
//配置路由地址
app.use(router)
app.use('/api', userRoutes)
app.use("/api", chatroomRoutes)
app.use("/api", messageRoutes)
app.use("/api", visitorRoutes)

// 初始化 Socket.IO
const io = initializeSocket(server)

// 使用 server 而不是 app 来监听
server.listen(5050, () => {
  console.log(`http://10.93.15.66:5050`)
  console.log("http://8.138.152.233:5050")
})
